package chessGame.utils;

import chessGame.annotation.PieceInfo;
import chessGame.piece.Piece;
import org.reflections.Reflections;

import java.lang.reflect.InvocationTargetException;

import org.reflections.scanners.Scanners;
import org.reflections.scanners.SubTypesScanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @BelongsProject: chessGame
 * @BelongsPackage: chessGame.utils
 * @CreateTime: 2025-10-08  21:45
 * @Description: 通过反射可以拿到所有带注释的棋子;
 * @Version: 1.0
 */
public class ReflectPiece {
    public static List<Piece> scanPiece(String packageName){
        List<Piece> pieceList = new ArrayList<>();
        try {
            //扫描指定路径的包
            Reflections reflections = new Reflections(packageName, Scanners.SubTypes,Scanners.TypesAnnotated);
            Set<Class<? extends Piece>> classes = reflections.getSubTypesOf(Piece.class);

            for (Class<? extends Piece> clazz : classes){
                if (clazz.getAnnotation(PieceInfo.class) != null){
                    String value = clazz.getAnnotation(PieceInfo.class).value();
                    pieceList.add(clazz.getDeclaredConstructor(String.class).newInstance(value));
                }
            }
        } catch (InstantiationException | IllegalAccessException e){
            System.err.println("棋子实例化异常" + e.getMessage());
        } catch (NoSuchMethodException e){
            System.err.println("找不到对应的构造方法" + e.getMessage());
        } catch (InvocationTargetException e){
            System.err.println("调用构造方法时发生错误" + e.getMessage());
        } catch (Exception e){
            System.err.println("未知错误" + e.getMessage());
        }
        return pieceList;
    }
}
